package com.qwz.learn;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Qiuwuzhi
 * @version V1.0
 * @Description: 享元工厂
 * @Package com.qwz.learn.FlyWeightFactory
 * @date 2019/12/23 15:17
 */
public class FlyWeightFactory {
    /**
     * 缓存多个FlyWeight对象
     */
    private Map<String, FlyWeight> fsmap = new HashMap<String, FlyWeight>();

    /**
     * 获取key对应的享元对象
     * @param key
     * @return
     */
    public FlyWeight getFlyWeight(String key) {
        //先从缓存中查找，是否存在key对应的FlyWeight对象
        FlyWeight flyWeight = fsmap.get(key);
        //存在直接返回

        //不存在
        if (flyWeight == null) {
            //创建新的FlyWeight对象
            flyWeight = new ConcreteFlyWeight(key);
            //写入缓存
            fsmap.put(key, flyWeight);
        }
        //返回
        return flyWeight;
    }
}

